package interceptcrossing.ui;

import interceptcrossing.Intercept;
import interceptcrossing.Intersection;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.Set;

public class IntersectionPanel extends JPanel implements MainWindowDirector.Listener {

	private JTable intersectionTable;
	private DefaultTableModel intersectionTableModel;
	private MainWindowDirector windowDirector;

	public IntersectionPanel(MainWindowDirector windowDirector) {
		this.windowDirector = windowDirector;
		this.windowDirector.addListener(this);

		this.intersectionTableModel = new DefaultTableModel(new String[][]{},
			new String[]{"Первый отрезок", "Второй отрезок", "Точка пересечения"});

		this.intersectionTable = new JTable(this.intersectionTableModel);
		this.intersectionTable.setRowSelectionAllowed(true);
		this.intersectionTable.setFillsViewportHeight(true);

		this.initLayout();
	}

	private void initLayout() {
		super.setLayout(new GridLayout(1, 1));
		super.add(new JScrollPane(this.intersectionTable));
	}

	public void currentInterceptChanged(int index, Intercept intercept) {
		//
	}

	public void interceptAdded(Intercept intercept) {
		this.clear();
	}

	public void interceptRemoved(Intercept intercept) {
		this.clear();
	}

	public void interceptsCleared() {
		this.clear();
	}

	public void intersectionsFound(Set<Intersection> intersections) {
		this.clear();

		for (Intersection intersection : intersections) {
			this.intersectionTableModel.addRow(new String[]{
				intersection.first().toString(),
				intersection.second().toString(),
				intersection.point().toString()
			});
		}
	}

	private void clear() {
		for (int i = this.intersectionTableModel.getRowCount() - 1; i >= 0; i--) {
			this.intersectionTableModel.removeRow(i);
		}
	}
}
